const axios = require('axios');
const path = require('path');
const fs = require('fs');

// const SWAGGER_API_URL = 'http://10.0.0.56:19001/weath/v2/api-docs';
const SWAGGER_API_URL = 'http://10.0.0.3/api/software/v2/api-docs';
// const SWAGGER_API_URL = 'http://192.168.1.13:18080/api/setting/v2/api-docs';
// const SWAGGER_API_URL = 'http://192.168.1.13/api/explorer/v2/api-docs';

const srcDir = path.resolve(__dirname, '../../src');
console.log(srcDir, 'src');
const apiDir = path.resolve(srcDir, 'api');
console.log('Creating API files...');

(async () => {
  // 排除的TAG
  const EXCLUDE_TAGS = ['authorize-flusher', 'internal'];
  const { data: swaggerData } = await axios.get(SWAGGER_API_URL);
  const { basePath } = swaggerData; // "/api/sd-equ"
  const SERVER_NAME = basePath.split('/').pop(); // "sd-equ"
  const API_SERVER_DIR = path.join(apiDir, SERVER_NAME);
  const { paths: dataPaths, tags: dataTags } = swaggerData;
  const tagsMap = {};
  dataTags.forEach((tag) => {
    if (!EXCLUDE_TAGS.includes(tag.name)) {
      tagsMap[tag.name] = [];
      const pathKeys = Object.keys(dataPaths);
      pathKeys.forEach((pathKey) => {
        const pathItem = dataPaths[pathKey];
        const methodKeys = Object.keys(pathItem);
        methodKeys.forEach((methodKey) => {
          const methodItem = pathItem[methodKey];
          const { tags: methodTags } = methodItem;
          if (methodTags.includes(tag.name)) {
            tagsMap[tag.name].push({
              path: pathKey,
              method: methodKey,
              methodItem
            });
          }
        });
      });
    }
  });
  const tagKeys = Object.keys(tagsMap);
  const apiFiles = [];
  tagKeys.forEach((tagKey) => {
    const tagItems = tagsMap[tagKey];
    // console.log(tagKey, tagItems);
    if (tagItems.length) {
      const modelName = tagItems[0].path.split('/')[1];
      const apiFile = path.join(API_SERVER_DIR, `${modelName}.js`);
      // eslint-disable-next-line
      const IMPORT_STR = `import request from '@/utils/request'`;
      const apiFileItem = {
        tag: tagKey,
        file: apiFile,
        contents: [IMPORT_STR]
      };
      tagItems.forEach((tagItem) => {
        // eslint-disable-next-line no-shadow
        const { path, method, methodItem } = tagItem;
        const { summary, tags } = methodItem;
        // eslint-disable-next-line no-shadow
        const generateApiMethodName = (path) => {
          // 路径转换大驼峰 /line/getById => lineGetById
          // eslint-disable-next-line no-shadow
          const pathToCamel = (path) => {
            const pathArr = path.split('/');
            const pathArrCamel = pathArr
              .filter((item) => item)
              .map((pathItem) => pathItem[0].toUpperCase() + pathItem.slice(1));
            const pathArrCamelStr = pathArrCamel.join('');
            return pathArrCamelStr.replace(pathArrCamelStr[0], pathArrCamelStr[0].toLowerCase());
          };
          return `${pathToCamel(path)}`;
        };
        // eslint-disable-next-line no-shadow
        const generateApiMethodBody = (path, method) => {
          const apiUrl = `/${SERVER_NAME}${path}`;
          if (method === 'get') {
            return `(params) => {
              return request.get("${apiUrl}", { params: {...params} });
            };`;
          }
          if (method === 'post' && path.endsWith('exportData')) {
            return `(body) => {
              return request.post("${apiUrl}", body, {
                responseType: "blob"
              });
            };`;
          }
          return `(body) => {
            return request.${method}("${apiUrl}", body);
          };`;
        };
        const apiStr = `// ${tags.join(',')} - ${summary}
        export const ${generateApiMethodName(path, method)} = ${generateApiMethodBody(path, method)}
        `;
        apiFileItem.contents.push(apiStr);
      });
      apiFiles.push(apiFileItem);
    }
  });
  // 写入文件
  apiFiles.forEach((apiFileItem) => {
    const { file, contents } = apiFileItem;
    const fileDir = path.dirname(file);
    if (!fs.existsSync(fileDir)) {
      fs.mkdirSync(fileDir, { recursive: true });
    }
    console.log('Writing file:', file);
    fs.writeFileSync(file, contents.join('\r\n'));
  });
  // console.log(sdEquData, apiFiles);
})();
